<template>
  <a-drawer
    :visible="visible"
    :title="title"
    width="600"
    :closable="false"
    @close="onClose"
    :destroyOnClose="true"
  >
    <a-form layout="vertical" :hideRequiredMark="true">
      <div class="text-title">
        提醒时间
        <a-tooltip>
          <template #title>
            <div>当日：账单逾期的当天提醒一次，后续不再提醒。</div>
            <div>每日：账单逾期之后的每天都发送提醒。</div>
          </template>
          <question-circle-outlined class="ml-5" />
        </a-tooltip>
      </div>
      <a-row style="width: 100%; margin-bottom: 10px" align="middle">
        <a-space :size="3">
          <a-col>逾期</a-col>
          <a-col>
            <a-select
              ref="select"
              v-model:value="modelRef.remind_json.condition_1"
              style="width: 50px"
              :size="'small'"
              @change="condition_1Change"
            >
              <a-select-option :value="1">前</a-select-option>
              <a-select-option :value="2">后</a-select-option>
            </a-select>
          </a-col>
          <a-col>
            <a-input-number
              id="inputNumber"
              v-model:value="modelRef.remind_json.day"
              :min="0"
              size="small"
              style="width: 70px"
              placeholder="请输入"
            />
          </a-col>
          <a-col>天，</a-col>
          <a-col>
            <a-select
              ref="select"
              v-model:value="modelRef.remind_json.condition_2"
              style="width: 60px"
              :size="'small'"
              @change="condition_2Change"
            >
              <a-select-option :value="1">当天</a-select-option>
              <a-select-option :value="2">每日</a-select-option>
            </a-select>
          </a-col>
          <a-col>
            <a-time-picker
              v-model:value="modelRef.remind_json.time"
              format="HH:mm"
              valueFormat="HH:mm"
              size="small"
              style="width: 95px"
          /></a-col>
          <a-col>提醒内容</a-col>
        </a-space>
      </a-row>
      <a-form-item v-bind="validateInfos.template_id">
        <template #label>
          <div class="text-title">选择模板</div>
        </template>
        <a-select
          v-model:value="modelRef.template_id"
          :options="templateOptions"
          placeholder="请选择模板"
        >
        </a-select>
      </a-form-item>
      <a-form-item>
        <template #label>
          <div class="text-title">通知内部人员</div>
        </template>
        <a-row style="margin-top: 5px">
          <a-radio-group
            v-model:value="modelRef.type"
            name="radioGroup"
            @change="radioChange"
          >
            <a-radio :value="1">合同经办人</a-radio>
            <a-radio :value="2">指定人员</a-radio>
            <a-radio
              :value="3"
              :disabled="typeDisabled"
              v-custom-directive="'参数'"
              >不通知内部人员</a-radio
            >
          </a-radio-group>
        </a-row>
        <a-row style="margin: 10px 0" v-if="modelRef.type == 2">
          <a-col
            class="institutional-personnel"
            v-for="(item, index) in userList"
            :key="item.uid"
          >
            <a-avatar :src="item.avatar" />
            <span class="user-name">{{ item.realname }}</span>
            <span>
              <close-outlined
                style="cursor: pointer"
                @click="closeUserClick(index)"
              />
            </span>
          </a-col>
          <a-col>
            <a-button type="primary" ghost class="add-user" @click="addUser">
              <template #icon><plus-outlined /></template>添加
            </a-button>
          </a-col>
        </a-row>
        <a-checkbox
          v-if="modelRef.type == 2"
          v-model:checked="modelRef.include_signer"
          >一并通知合同经办人（如果指定人员中包含经办人不重复提醒）</a-checkbox
        >
      </a-form-item>
      <a-form-item v-bind="validateInfos.is_send_owner">
        <template #label>
          <div class="text-title">
            通知{{ $L("租客") }}
            <a-tooltip>
              <template #title>
                通知{{
                  $L("租客")
                }}时默认通知账单联系人，当账单联系未找到时，则提示默认联系人
              </template>
              <question-circle-outlined class="ml-5" />
            </a-tooltip>
          </div>
        </template>
        <a-select
          ref="select"
          v-model:value="modelRef.is_send_owner"
          @change="sendOwnerChange"
        >
          <a-select-option :value="1">是</a-select-option>
          <!--  :disabled="sendOwner" -->
          <a-select-option :value="0">否</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <a-row style="margin-top: 10px; margin-bottom: 5px">
      <div class="text-title">模板状态</div>
    </a-row>
    <a-switch
      v-model:checked="modelRef.status"
      checked-children="开"
      un-checked-children="关"
      :checkedValue="1"
      :unCheckedValue="0"
    />
    <div class="drawer-footer">
      <a-button class="mr-10" @click="onClose">取消</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </div>

    <!-- 岗位添加成员 -->
    <ChooseOrgMember
      @request="$utils.commonRequest"
      :visible="addMemberVisible"
      :deptDisabled="true"
      :uids="selectedUids"
      setUids="uncheck"
      :getDetail="true"
      @close="handleAddMemberClose"
      @success="handleAddMemberSuccess"
    />
  </a-drawer>
</template>

<script>
import { reactive, toRefs, defineComponent, computed, watch } from "vue";
import {
  CloseOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { ChooseOrgMember } from "bl-common-vue3";
import { Form, message } from "ant-design-vue";
import request from "../../../../common/utils/request";
const useForm = Form.useForm;

let isSendOwner = 1;
const customDirective = {
  mounted(el, binding) {
    // 指令逻辑
    el.addEventListener("click", (e) => {
      // 点击时触发的逻辑
      if (!isSendOwner) {
        message.warn("请至少选择一种通知对象");
      }
    });
  },
};
export default defineComponent({
  directives: {
    "custom-directive": customDirective,
  },
  name: "AddPayment",
  components: {
    CloseOutlined,
    PlusOutlined,
    ChooseOrgMember,
    QuestionCircleOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    detail: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props, context) {
    const state = reactive({
      count: 0,
      pickerValue: "",
      addMemberVisible: false,
      selectedUids: [],
      userList: [],
      templateOptions: [],
      sendOwner: false,
      typeDisabled: false,
    });

    const modelRef = reactive({
      remind_json: {
        condition_1: 1,
        condition_1_txt: "前",
        day: "",
        condition_2: 1,
        condition_2_txt: "当天",
        time: "",
      },
      status: 1,
      is_send_owner: 1,
      template_id: undefined,
      org_user: [],
      village_id: props.detail.id,
      type: 1,
      include_signer: false,
    });
    const rulesRef = reactive({
      template_id: [
        {
          required: true,
          message: "请选择模板",
        },
      ],
      is_send_owner: [
        {
          required: false,
        },
      ],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const condition_1Change = (key) => {
      modelRef.remind_json.condition_1_txt = key == 1 ? "前" : "后";
    };

    const condition_2Change = (key) => {
      modelRef.remind_json.condition_2_txt = key == 1 ? "当天" : "每日";
    };

    const radioChange = ({ target }) => {
      state.sendOwner = false;
      if (target.value == 3 && !state.typeDisabled) {
        state.sendOwner = true;
      }
    };

    const sendOwnerChange = (value, e) => {
      if (!value && modelRef.type == 3) {
        modelRef.is_send_owner = 1;
        message.warn("请至少选择一种通知对象");
        return;
      }
      isSendOwner = value;
      state.typeDisabled = false;
      if (value == 0) {
        state.typeDisabled = true;
      }
    };

    const onClose = () => {
      resetFields();
      context.emit("closeChange");
    };

    const onSubmit = () => {
      if (!modelRef.remind_json.day) {
        message.error("请输入逾期天数");
        return;
      }
      if (!modelRef.remind_json.time) {
        message.error("请选择时间");
        return;
      }
      validate().then(() => {
        if (modelRef.type == 2 && !state.userList.length) {
          message.warn("请选择机构人员");
          return;
        }
        if (modelRef.type != 2) {
          modelRef.org_user = [];
          modelRef.include_signer = false;
        }
        if (props.detail.edit) {
          modelRef.id = props.detail.id;
          request.put("/org", "/notice/remindEdit", modelRef).then((res) => {
            message.success("编辑成功");
            resetFields();
            context.emit("submitChange");
          });
          return;
        }
        request.post("/org", "/notice/remindAdd", modelRef).then((res) => {
          message.success("添加成功");
          resetFields();
          context.emit("submitChange");
        });
      });
    };

    const addUser = () => {
      if (state.userList.length) {
        state.selectedUids = state.userList.map((item) => item.uid);
      } else {
        state.selectedUids = [];
      }
      state.addMemberVisible = true;
    };

    const closeUserClick = (index) => {
      state.userList.splice(index, 1);
      modelRef.org_user = state.userList.map((item) => {
        return {
          uid: item.uid,
          realname: item.realname,
          avatar: item.avatar,
        };
      });
    };

    const handleAddMemberClose = () => {
      state.addMemberVisible = false;
    };
    const handleAddMemberSuccess = (data) => {
      if (data.user.length) {
        state.userList = data.user;
        modelRef.org_user = state.userList.map((item) => {
          return {
            uid: item.uid,
            realname: item.realname,
            avatar: item.avatar,
          };
        });
      }
      handleAddMemberClose();
    };

    const getSendList = () => {
      request
        .get("/org", "/notice/sendList", {
          page: 1,
          limit: 100000,
        })
        .then((res) => {
          state.templateOptions = res.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
            };
          });
        });
    };

    const title = computed(() => {
      return `${props.detail.name}-${
        props.detail.edit ? "编辑" : "新增"
      }自动催缴配置模板`;
    });

    const sendModelRef = (detail) => {
      modelRef.remind_json = detail.remind_json;
      modelRef.template_id = detail.template_id;
      modelRef.org_user = detail.org_user;
      state.userList = detail.org_user || [];
      modelRef.is_send_owner = detail.is_send_owner;
      state.typeDisabled = detail.is_send_owner == 0 ? true : false;
      isSendOwner = detail.is_send_owner;
      modelRef.village_id = detail.village_id;
      modelRef.status = detail.status;
      modelRef.type = detail.type;
      modelRef.include_signer = detail.include_signer ? true : false;
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getSendList();
          if (props.detail.id) {
            modelRef.village_id = props.detail.id;
          }
          if (props.detail.edit) {
            sendModelRef(JSON.parse(JSON.stringify(props.detail)));
          }
        } else {
          state.userList = [];
        }
      }
    );

    return {
      ...toRefs(state),
      title,
      onClose,
      onSubmit,
      modelRef,
      validateInfos,
      handleAddMemberClose,
      handleAddMemberSuccess,
      addUser,
      closeUserClick,
      condition_1Change,
      condition_2Change,
      sendOwnerChange,
      radioChange,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.ant-form-item-label) {
  padding: 0px !important;
}
:deep(.ant-form-item) {
  margin-bottom: 15px !important;
}
.institutional-personnel {
  background: #f1f1f1;
  margin-right: 10px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  padding-right: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  .user-name {
    margin: 0 10px;
  }
  .add-user {
    height: 32px;
    border: 1px solid #4e50e8;
    color: #4e50e8;
  }
}
</style>
